package main

import (
	"fmt"
	"sync"
)

func worker(id int, c chan int, wg *sync.WaitGroup) {
	defer wg.Done()

	for {
		data, ok := <-c
		if !ok {
			// channel已关闭
			break
		}
		fmt.Printf("Worker %d received %d\n", id, data)
	}
}

func chanDemo() {
	c := make(chan int)

	var wg sync.WaitGroup
	wg.Add(1)

	go worker(1, c, &wg)

	// 向通道发送数据
	for i := 0; i < 10; i++ {
		c <- i
	}

	// 关闭通道，通知goroutine停止接收
	close(c)

	// 等待goroutine完成
	wg.Wait()
}

func main() {
	chanDemo()

	fmt.Println("All goroutines completed.")
}
